package com.sefer.dragonfly.client.tools;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;

import com.sefer.dragonfly.client.core.domain.LogData;
import com.sefer.dragonfly.client.core.listener.Listener;
import com.sefer.dragonfly.client.core.listener.Listenerable;
import com.sefer.dragonfly.client.core.listener.event.CMonitorEvent;
import com.sefer.dragonfly.client.core.listener.event.Event;
import com.sefer.dragonfly.client.core.listener.event.EventContext;
import com.sefer.dragonfly.client.core.listener.event.EventType;

/**
 * <pre>
 * 数据采集，数据可以是对象. 
 * 
 * 注： 工具类调用toString方法来获得string值，所以请重载toString方法
 * </pre>
 * 
 * @author xiaofeng 2011-11-3 下午03:55:09
 */
public class MonitorLog implements Listenerable {
	private List<Listener> listenerList;
	private String cacheId;

	public MonitorLog(String cacheId) {
		super();
		this.cacheId = cacheId;
	}

	public void log(Serializable o) {
		log(o, 60 * 30);
	}

	public void log(Serializable o, int timeout) {
		if (o != null) {
			// 记录
			o.toString();
			for (Listener listener : listenerList) {
				listener.onFire(new Event<Object>(new EventContext<Object>(
						new LogData(o, cacheId, timeout),
						CMonitorEvent.ADD_CACHE_DATA)));
			}
		}
		// 传入对象为空则忽略
	}

	/**
	 * 处理数据的监听器,可以扩展实现自己的EventType和Listener
	 * 
	 * @see CMonitorEvent
	 * @see EventType
	 */
	public void addListener(Listener listener) {
		synchronized (MonitorLog.class) {
			if (listenerList == null) {
				listenerList = new LinkedList<Listener>();
			}
		}

		listenerList.add(listener);
	}
}
